package com.change.core.jackson;

import cn.hutool.core.util.StrUtil;
import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.databind.DeserializationContext;
import com.fasterxml.jackson.databind.deser.std.StdDeserializer;

import java.io.IOException;
import java.time.Instant;
import java.time.LocalDateTime;
import java.time.ZoneId;

/**
 * LocalDateTimeDeserializer
 *
 * @author linqunxun
 * @date 2021/9/18 5:39 下午
 */
public class LocalDateTimeDeserializer extends StdDeserializer<LocalDateTime> {
    public LocalDateTimeDeserializer() {
        super(LocalDateTime.class);
    }

    @Override
    public LocalDateTime deserialize(final JsonParser parser,
                                     final DeserializationContext context) throws IOException {
        String text = parser.getText();
        if (StrUtil.isEmpty(text)) {
            return null;
        }
        try {
            Long value = Long.parseLong(text);
            return LocalDateTime.ofInstant(Instant.ofEpochMilli(value), ZoneId.systemDefault());
        } catch (NumberFormatException e) {
            throw new RuntimeException("日期时间格式有误！");
        }
    }
}
